#!/usr/bin/env python3
"""
验证Flight策略"数据不足，跳过分析"问题修复
"""

def verify_flight_fix():
    print("🔧 验证Flight策略修复效果")
    print("=" * 60)
    
    # 测试1: Flight策略独立运行
    print("\n1️⃣ 测试Flight策略独立运行...")
    try:
        from flight_strategy import init_flight_strategy, get_flight_ohlcv_data, analyze_with_flight
        
        if init_flight_strategy():
            print("   ✅ Flight策略初始化成功")
            
            data = get_flight_ohlcv_data('BTC/USDT:USDT')
            if data:
                print(f"   ✅ 数据获取成功 - 价格: ${data['price']:,.2f}")
                
                signal = analyze_with_flight(data, 'BTC/USDT:USDT')
                if signal:
                    print(f"   ✅ 分析成功 - 信号: {signal['signal']}")
                else:
                    print("   ❌ 分析失败")
                    return False
            else:
                print("   ❌ 数据获取失败")
                return False
        else:
            print("   ❌ Flight策略初始化失败")
            return False
            
    except Exception as e:
        print(f"   ❌ 独立运行测试失败: {e}")
        return False
    
    # 测试2: 多账号管理器集成
    print("\n2️⃣ 测试多账号管理器集成...")
    try:
        from multi_account_manager import TradingAccount
        import json
        import logging
        
        # 读取配置
        with open('accounts_config.json', 'r') as f:
            config = json.load(f)
        
        # 查找Flight策略账户
        flight_account = None
        for aid, acfg in config['accounts'].items():
            if acfg.get('strategy') == 'flight' and acfg.get('enabled', False):
                flight_account = (aid, acfg)
                break
        
        if flight_account:
            account_id, account_config = flight_account
            print(f"   ✅ 找到Flight策略账户: {account_id}")
            
            # 创建交易账户实例
            main_logger = logging.getLogger('verify_test')
            account = TradingAccount(account_id, account_config, main_logger)
            
            if account.init_exchange():
                print("   ✅ 交易所初始化成功")
                
                # 创建策略状态
                from deepseek import create_strategy_state
                account.telegram_runtime = account._build_telegram_runtime_config()
                account.strategy_state = create_strategy_state(
                    trade_config=account.config['config'],
                    exchange_instance=account.exchange,
                    telegram_config=account.telegram_runtime,
                    sandbox=account.config.get('sandbox', True),
                    account_id=account.account_id,
                )
                print("   ✅ 策略状态创建成功")
                
                # 测试Flight策略数据获取（修复的关键部分）
                symbol_config = account.strategy_state.trade_config['symbols'][0]
                symbol = symbol_config['symbol']
                print(f"   📊 测试交易对: {symbol}")
                
                # 这里会调用修复后的代码
                # 临时捕获日志来检查是否还有"数据不足"错误
                import io
                import sys
                
                # 重定向日志输出
                log_capture = io.StringIO()
                handler = logging.StreamHandler(log_capture)
                account.logger.addHandler(handler)
                
                try:
                    account.analyze_and_trade()
                    log_output = log_capture.getvalue()
                    
                    # 检查是否还有"数据不足"错误
                    if "Flight策略数据不足，跳过分析" in log_output:
                        print("   ❌ 仍然存在'数据不足'错误")
                        print(f"   日志: {log_output}")
                        return False
                    else:
                        print("   ✅ Flight策略数据获取正常，无'数据不足'错误")
                        
                finally:
                    account.logger.removeHandler(handler)
                
            else:
                print("   ❌ 交易所初始化失败")
                return False
        else:
            print("   ❌ 未找到启用的Flight策略账户")
            return False
            
    except Exception as e:
        print(f"   ❌ 多账号集成测试失败: {e}")
        import traceback
        traceback.print_exc()
        return False
    
    return True

if __name__ == "__main__":
    print("🎬 Flight策略修复验证")
    print(f"验证时间: {__import__('datetime').datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
    print("=" * 80)
    
    success = verify_flight_fix()
    
    print("\n" + "=" * 80)
    print("🎊 验证结果")
    print("=" * 80)
    
    if success:
        print("🎉 Flight策略'数据不足，跳过分析'问题已修复！")
        print("\n✅ 修复内容:")
        print("   1. Flight策略独立运行正常")
        print("   2. 多账号管理器集成正常")
        print("   3. 数据获取功能正常")
        print("   4. 不再出现'数据不足'错误")
        
        print("\n🚀 可以正常使用:")
        print("   - python flight_strategy.py (独立运行)")
        print("   - python multi_account_manager.py (多账号运行)")
        print("   - python demo_flight_strategy.py (演示模式)")
        
    else:
        print("⚠️ Flight策略仍有问题需要进一步修复")
